package com.demo.smart;

import org.smartboot.socket.MessageProcessor;
import org.smartboot.socket.Protocol;
import org.smartboot.socket.transport.AioQuickServer;
import org.smartboot.socket.transport.AioSession;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.*;

public class Server {
    private static final Map<String, AioSession> map = new HashMap<>();
    public static void main(String[] args) throws IOException {
        MessageProcessor<String> processor = (session, msg) -> {
            System.out.println("处理消息("+session.getSessionID()+"):"+msg);
        };

        AioQuickServer server = new AioQuickServer(9695, new StringProtocol(), processor);
        server.setReadBufferSize(1024);
        server.setLowMemory(true);//低内存模式下，关闭session会报错
        Timer timer = new Timer();
        // 创建定时器任务
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                if(!map.isEmpty()){
                    map.forEach((id,session)->{
                        System.out.println("关闭session:"+id);
                        session.close(true);
                    });
                }

            }
        };

        timer.schedule(timerTask, 10000);
        server.start();

    }
    public static class StringProtocol implements Protocol<String> {

        @Override
        public String decode(ByteBuffer byteBuffer, AioSession session) {
            if(!map.containsKey(session.getSessionID())){
                map.put(session.getSessionID(), session);
            }
            byte[] bytes = new byte[byteBuffer.remaining()];

            byteBuffer.get(bytes);
            return new String(bytes, StandardCharsets.UTF_8);

        }
    }
}
